/**
 * 目标1：渲染图书列表
 *  1.1 获取数据
 *  1.2 渲染数据
 */



const creator = '李政轩'
const list = document.querySelector('.list')
// 封装一个函数 渲染页面
const fn =  () => {
  axios({
    url: 'http://hmajax.itheima.net/api/books',
    method: 'GET',
    params:{creator}
  }).then(({ data: { data } }) => {
    // console.log(res.data.data)
    // const { data: { data } } = res
    // console.log(data)
    list.innerHTML = data.map((item, index) => {
      const {bookname,author,publisher,id} = item
      return `
        <tr>
          <td>${index + 1}</td>
          <td>${bookname}</td>
          <td>${author}</td>
          <td>${publisher}</td>
          <td data-id = ${id}>
            <span class="del">删除</span>
            <span class="edit">编辑</span>
          </td>
        </tr>
      `
    }).join('')
  })
}
fn()


// 2.1点击添加按钮弹出模态框 => js控制 存在额外操作
const addBtn = document.querySelector('.add-btn')
const addForm = document.querySelector('.add-form')
const myModalDom = document.querySelector('.add-modal')
const myModal = new bootstrap.Modal(myModalDom)
addBtn.addEventListener('click', e => {
  const data = serialize(addForm, { hash: true, empty: true })
  if (!data.author || !data.bookname || !data.publisher) {
  alert('不能为空')
}
  // console.log(data);
  axios({
    url: 'http://hmajax.itheima.net/api/books',
    method: 'POST',
    data: {
      creator,
      ...data
    }
  }).then(res => {
    // console.log(res);
    myModal.hide()
    fn()
    addForm.reset()
  })
})

//  目标3.删除图书
// 3.1 给删除按钮绑定时间 => 时间委托 => 删除按钮是后追加的元素,所以不能直接获取,需要给父级添加时间委托
list.addEventListener('click', e => {
  const { target, target: { parentNode: { dataset } } } = e
  if (target.classList.contains('del')) {
    // 3.2获取当前数据的id值
    console.log(dataset.id)
    // 3.3发请求,删数据
    axios({
      // path参数叫做路径参数,就将参数写在url后面
      url: `http://hmajax.itheima.net/api/books/${dataset.id}`,
      method:'DELETE'
    }).then(res => {
      // alert(res.data.messages)
      alert(res.data.message)
      // 重新渲染页面
      fn()
    })
  }
})


// 目标4:编辑图书
// 4.1点击编辑按钮 显示模态框 => js控制i单机后执行其他的逻辑
// 4.2 显示模态框后，根据这个id 获取图书详情
const editModal = new bootstrap.Modal(document.querySelector('.edit-modal'))
const editForm = document.querySelector('.edit-form')
list.addEventListener('click', e => {
  const {target:{classList,parentNode:{dataset}}} = e
  if (classList.contains('edit')) {
    // console.log(e.target.parentNode.dataset.id)
    // const id = e.target.parentNode.dataset.id
    editModal.show()
    axios({
      url:`http://hmajax.itheima.net/api/books/${dataset.id}`,
      method: 'GET',
    }).then(res => {
      // console.log(res)
      const { data } = res.data
      // const arr = Object.keys(data)
      // console.log(arr)
      Object.keys(data).forEach(item => { 
        // console.log(item)
        editForm.querySelector(`[name = ${item}]`).value = data[item]
      })
    })
  }
})
document.querySelector('.edit-btn').addEventListener('click', e => {
  const data = serialize(editForm, { hash: true, empty: true })
  console.log(data)
  // 2.通过AJAX发送数据给服务器做修改
  axios({
    url: `http://hmajax.itheima.net/api/books/${data.id}`,
    method: 'PUT',
    data: {
      creator,
      ...data
    }
  }).then(res => {
    // console.log(res)
    // 关闭弹框
    editModal.hide()
    // 渲染页面
    fn()
    // 清空表单
    editForm.submit().reset()
  })
})























/*
const creator = '张玲';
const list = document.querySelector('.list');
const modal = document.querySelector('.modal');
const modalContent = document.querySelector('.modal-content');
const modalSaveBtn = document.querySelector('.modal-save');
const modalCancelBtn = document.querySelector('.modal-cancel');


// 封装一个函数 渲染页面
const fn = () => {
  axios({
    url: 'http://hmajax.itheima.net/api/books',
    method: 'GET',
    params: { creator }
  }).then(({ data: { data } }) => {
    list.innerHTML = data.map((item, index) => {
      const { bookname, author, publisher } = item;
      return `
        <tr>
          <td>${index + 1}</td>
          <td>${bookname}</td>
          <td>${author}</td>
          <td>${publisher}</td>
          <td>
            <span class="edit" data-index="${index}">编辑</span>
            <span class="del" data-index="${index}">删除</span>
          </td>
        </tr>
      `;
    }).join('');

    // 绑定编辑和删除按钮的点击事件
    const editBtns = document.querySelectorAll('.edit');
    const delBtns = document.querySelectorAll('.del');

    editBtns.forEach(btn => {
      btn.addEventListener('click', handleEdit);
    });

    delBtns.forEach(btn => {
      btn.addEventListener('click', handleDelete);
    });
  });
};

// 处理编辑按钮点击事件
const handleEdit = (event) => {
  const index = event.target.dataset.index;
  const book = list.children[index];
  const bookname = book.children[1].textContent;
  const author = book.children[2].textContent;
  const publisher = book.children[3].textContent;

  // 显示模态框
  modal.style.display = 'block';

  // 在模态框中显示当前选中的图书信息
  modalContent.innerHTML = `
    <label for="bookname">书名：</label>
    <input type="text" id="bookname" value="${bookname}">
    <label for="author">作者：</label>
    <input type="text" id="author" value="${author}">
    <label for="publisher">出版社：</label>
    <input type="text" id="publisher" value="${publisher}">
  `;

  // 绑定保存和取消按钮的点击事件
  modalSaveBtn.addEventListener('click', handleSave);
  modalCancelBtn.addEventListener('click', handleCancel);
};

// 处理保存按钮点击事件
const handleSave = () => {
  // 获取模态框中的输入值
  const bookname = document.getElementById('bookname').value;
  const author = document.getElementById('author').value;
  const publisher = document.getElementById('publisher').value;

  // 根据用户的操作进行相应的处理，比如发送请求更新图书信息

  // 隐藏模态框
  modal.style.display = 'none';

  // 重新渲染页面
  fn();
};

// 处理取消按钮点击事件
const handleCancel = () => {
  // 隐藏模态框
  modal.style.display = 'none';
};

// 处理删除按钮点击事件
const handleDelete = (event) => {
  const index = event.target.dataset.index;
  const book = list.children[index];
  const bookname = book.children[1].textContent;

  // 根据用户的操作进行相应的处理，比如发送请求删除图书信息

  // 重新渲染页面
  fn();
};

fn();
*/

